import React, { useEffect, useState } from 'react';
import { Button, Dialog, ResponsiveGrid, Icon } from '@alifd/next';
import { observer } from 'mobx-react-lite';
import { t } from '@lingui/macro';
import { column, model } from '../stores/definitions';
import { TitleGrid } from '@/stores/definitions-base';
import UploadPanel from '@/components/UploadPanel';
import TauTable from '@/components/TauTable';
import AttachmentForm from './AttachmentForm';

const { Cell } = ResponsiveGrid;

const AttachmentPanel = observer(({ station, mode }) => {
  const [curAttachment, setCurAttachment] = useState();
  const [idx, setIdx] = useState(-1); // 当前选中的附件
  const isViewMode = mode === 'check';

  useEffect(() => {
    if (station?.attachments?.length) setIdx(0);
  }, [station?.attachments]);

  const handleAddAttachment = () => {
    if (!station?.attachments) station.attachments = [];
    station.attachments.push({ title: t`附件`, description: t`附件说明`, binaryId: [] });
    setIdx(station.attachments.length - 1);
  };

  const handleDeleteAttachment = (i, e) => {
    station.attachments.splice(i, 1);
    if (i === idx) setIdx(i - 1);
    e.preventDefault();
    e.stopPropagation();
  };

  return (
    <>
      <TitleGrid style={{ width: 260, fontSize: 16, fontWeight: 500 }} title={<span>{t`附件`}{mode !== 'view' && <Button type="primary" style={{ marginLeft: 24 }} onClick={handleAddAttachment} >{t`添加附件`}</Button>}</span>} />
      <ResponsiveGrid gap={[0, 30]} style={{ paddingLeft: 20 }}>
        <Cell colSpan={10}>
          <TauTable
            primaryKey="orderNumber"
            size="small"
            hidePagination
            tableLayout="fixed"
            dataSource={toJS(station?.attachments)}
            cellProps={(r) => ({ style: { cursor: 'pointer', backgroundColor: idx === r ? 'var(--color-fill1-1)' : 'unset' } })}
            columns={[
              { title: '#', dataIndex: 'idx', width: 44, cell: (_, i) => i + 1 },
              column('title', {}, model?.attachments[0]),
              column('description', {}, model?.attachments[0]),
              { title: t`附件个数`, dataIndex: 'cnt', width: 84, cell: (_, i, row) => <Button type="primary" text>{row.binaryId?.length}</Button> },
            ].concat(isViewMode ? [{ align: 'left', width: 30, cell: (_, i) => (i === idx && <Icon type="arrow-right" size="xs" style={{ color: 'var(--color-line1-4)' }} />) }] : [
              {
                title: <span style={{ paddingLeft: 16 }}>{t`操作`}</span>,
                dataIndex: 'title',
                align: 'left',
                width: 110,
                cell: (_, i, row) => (
                  <span>
                    <Button type="primary" text onClick={() => setCurAttachment(row)} >{t`编辑`}</Button>
                    <span>  </span>
                    <Button type="primary" text onClick={(e) => handleDeleteAttachment(i, e)} >{t`删除`}</Button>
                    {i === idx && <Icon type="arrow-right" size="xs" style={{ marginLeft: 16, color: 'var(--color-line1-4)' }} />}
                  </span>
                ),
              },
            ])}
            onRowClick={(_, index) => setIdx(index)}
          />
        </Cell>
        <Cell colSpan={5} style={{ paddingTop: 30 }}>
          {idx >= 0 && <UploadPanel
            isPreview={isViewMode}
            prefix={`station:${station.id}:attachment`}
            binaryIds={idx === -1 ? [] : toJS(station.attachments[idx]?.binaryId)}
            onUploaded={(meta) => {
              station.attachments[idx]?.binaryId.push(meta.binaryId);
            }}
            onRemove={(info) => {
              station.attachments[idx]?.binaryId.splice(station.attachments[idx]?.binaryId.findIndex((r) => r == info.uid), 1);
            }}
          />}
        </Cell>
      </ResponsiveGrid>
      <Dialog
        visible={!!curAttachment}
        onCancel={() => setCurAttachment(false)}
        onClose={() => setCurAttachment(false)}
        title={t`附件`}
        style={{ width: '50%' }}
        footer={null}
      >
        <AttachmentForm
          data={curAttachment}
          onSubmit={(data) => {
            _.assign(station.attachments[idx], data);
            setCurAttachment(false);
          }}
          onCancel={() => setCurAttachment(false)}
        />
      </Dialog>
    </>
  );
});

export default AttachmentPanel;
